#include<iostream>
#include<string>
#include<cerrno>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>
using namespace std;
void Usage(string proc)
{
    cout<<"Usage:\n\t"<<proc<<"server_ip server_port"<<endl;
}

// ./udp_client  sercer_ip server_proc
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[3]);return 0;
    }

    //1.创建socket,打开网络文件
    int sock=socket(AF_INET,SOCK_DGRAM,0);
    if(sock<0)
    {
        cerr<<"socket error:"<<errno<<endl; return 1;
    }
      
    //客户端不需要自己绑定，client发消息的时候OS会自动绑定，采用随机端口的方式

    //和谁发消息
    struct sockaddr_in server;
    server.sin_family=AF_INET;
    server.sin_port=htons(atoi(argv[2]));//先转整数再转为网络序列
    server.sin_addr.s_addr=inet_addr(argv[1]);//server的IP

    while(1)
    {
        // string message;
        // cout<<"输入#：";
        // cin>>message;
        cout<<"my shell $:";
        char line[1024];
        fgets(line,sizeof(line),stdin);
        sendto(sock,line,strlen(line),0,(struct sockaddr*)&server,sizeof(server));

        struct sockaddr_in tmp;
        socklen_t len=sizeof(tmp);
        char buffer[1024];
        size_t cnt=recvfrom(sock,buffer,sizeof(buffer),0,(struct sockaddr*)&tmp,&len);
        if(cnt>0)
        {
            //在网络通信中,只有报文的大小/字节流中字节的个数,没有字符串的概念
            buffer[cnt]=0;
            cout<<buffer<<endl;
        }else{

        }
    }
    return 0;

}